package merchant

import (
	"context"
	"encoding/json"

	"system-admin/config/mysql"
	"system-admin/config/redis"
	"system-admin/internal/define"
	"system-admin/internal/models"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/helper"
)

// CreateAPIToken 生成商户的api token
func CreateAPIToken(loginUserID, merchantID string) (token string, err error) {
	var loginUser models.User
	mysql.NewDB().Model(&models.User{}).Where("id = ?", loginUserID).Take(&loginUser)
	if loginUser.IsSuperAdmin != 1 {
		return "", errorx.New("无权限", -1)
	}
	if merchantID == "" {
		return "", errorx.New("商户id不能为空", -1)
	}
	token = helper.RandString(32)
	rowsAffected := mysql.NewDB().Model(&models.Merchant{}).
		Where("id = ?", merchantID).
		Update("api_token", token).
		RowsAffected
	if rowsAffected <= 0 {
		return "", errorx.New("生成接口秘钥失败", -1)
	}
	return token, nil
}

// 加载商户接口秘钥到redis
func LoadMerchantAPITokenToRedis() {
	var merchants []struct {
		ID       string `json:"merchant_id" gorm:"column:id"`
		APIToken string `json:"-" gorm:"column:api_token"`
	}
	mysql.NewDB().Model(&models.Merchant{}).
		Select(
			"id",
			"api_token",
		).
		Find(&merchants)

	var values []interface{}
	for _, merchant := range merchants {
		dataBytes, _ := json.Marshal(merchant)
		values = append(values, merchant.APIToken, string(dataBytes))
	}
	redis.NewDB().HMSet(context.Background(), define.RedisMerchantAPITokenList, values...)
}
